import axios from 'axios'
import Qs from 'qs'
import {Message, MessageBox} from 'element-ui'
import store from '../store'
import {getToken} from './auth'
import {env} from '../env'

const service = axios.create({
  baseURL: env.VUE_APP_BASE_URL,
  timeout: 1500000, // ms
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  transformRequest: [function (data) {
    return Qs.stringify(data);
  }],
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['X-Token'] = getToken()
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
    const res = response.data
    if (!!res.code && res.code !== 1) {
      // 提示错误
      Message({message: res.msg, type: 'error', duration: 5 * 1000});

      // 需要用户
      if (res.code === 40005) {
        MessageBox.confirm(res.msg, '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject('error')
    } else {
      return response;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
